import { CSSProperties, ReactNode, useMemo } from "react";
export const highlight_style: CSSProperties = {
  background: 'yellow', fontWeight: 'bolder', color: 'black', border: '1px solid black'
}
export interface IHighLightTextProps {
  search?: Unsafe<string>;
  children?: Unsafe<string>;
}
export function HighLightText(props: IHighLightTextProps): ReactNode {
  const { children, search } = props
  return useMemo(() => {
    if (!search || !children || children.indexOf(search) < 0)
      return children || void 0;
    const regexp = new RegExp(search, 'g');
    let match;
    const label_children: React.ReactNode[] = [];
    let prev_index = 0;
    while ((match = regexp.exec(children)) !== null) {
      const normal_str = children.substring(prev_index, match.index);
      if (normal_str) label_children.push(normal_str);
      const highlight_str = children.substring(match.index, regexp.lastIndex);
      label_children.push(
        <b key={label_children.length} style={highlight_style}>
          {highlight_str}
        </b>
      );
      prev_index = regexp.lastIndex;
    }
    const normal_str = children.substring(prev_index, children.length);
    if (normal_str) label_children.push(normal_str);
    return <>{label_children}</>;
  }, [children, search])
}
